package com.by.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.by.block.OrderBlockHandler;
import com.by.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.ObjDoubleConsumer;

/**
 * @author ServivE
 * @version 0.1
 * @className OrderController
 * @description
 * @date 2024/10/31 20:25
 * @since jdk17
 */
@RestController
public class OrderController {

    @Autowired
    OrderService orderService;

    /**
     * blockHandler 当访问量超过 流量控制指定的闽值 报异常 执行该参数指定 的方法
     * fallback 异常降级处理
     *
     * @param id
     * @return
     */
    @GetMapping("order")
    @SentinelResource(value = "查询订单", blockHandler = "queryFail", blockHandlerClass = {OrderBlockHandler.class},
            fallback = "handlerError",fallbackClass = {OrderBlockHandler.class},exceptionsToIgnore = {NullPointerException.class})
    public Map query(int id) {
        System.out.println("id===" + id);
        /*String tmp = null;
        System.out.println(tmp.length());*/
        return orderService.get();
    }


    /**
     * 限流后的逻辑
     *
     * @param id
     * @param e
     * @return
     */
    /*public Map queryFail(int id ,BlockException e) {
        System.out.println("id===" + id);
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "服务器繁忙");
        return map;
    }*/

    /**
     * 异常处理
     *
     * @param id
     * @param e
     * @return
     */
    /*public Map handlerError(int id, Throwable e) {
        System.out.println("================fallback==========");
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "异常处理：" + e.getMessage());
        return map;
    }*/
    @PostConstruct //相当于spring bean中的   init方法 在类实例化调用 且只调用一次
    public void init() {
        List<FlowRule> rules = new ArrayList<>();
        //定义规则
        FlowRule rule = new FlowRule();
        rule.setResource("查询订单");//给指定资源设置规则
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//设置阈值类型  qps
        rule.setCount(1);//阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式 默认直接模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果 默认直接拒绝
        rules.add(rule);
        FlowRuleManager.loadRules(rules);

    }
}
